// miniprogram/pages/shopSettings/shopSettings.js
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopState: {
      name: 'shopState',
      list: ['正常营业', '暂停营业'],
      val: '正常营业'
    },
    reserve: {
      name: 'reserve',
      list: ['开启预约', '关闭预约'],
      val: '开启预约'
    },
    deliver: {
      name: 'deliver',
      list: ['开启外卖', '关闭外卖'],
      val: '开启外卖'
    },
    deliveryRules: []
    //openTime:'00:00',
    //closeTime:'00:00',
    //phone:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let that = this
    //--------------------------------加载过程中，重新获取settings
    wx.showLoading({
      title: '正在加载'
    })
    util.queryShopSettings().then(res => {
        wx.hideLoading();
        //将数据库中存储的设置显示至当前设置页面
        let settings = res.data
        that.setData({
          //-------------------1.设置营业时间
          openTime: settings.openTime,
          closeTime: settings.closeTime,
          //-------------------2.设置营业状态
          'shopState.val': settings.shopState,
          'reserve.val': settings.reserve,
          'deliver.val': settings.deliver,
          //-------------------3. 设置外卖标准收费时间段
          normalTimeStart: settings.normalTimeStart,
          normalTimeEnd: settings.normalTimeEnd,
          extraDeliveryCost: Number(settings.extraDeliveryCost), //超出时间段每单加价
          //-------------------4. 设置配送限制
          sendDistance: Number(settings.sendDistance), //派送距离
          //-------------------5. 设置店铺设置
          slogan: settings.slogan, //店铺标语
          mainCamp: settings.mainCamp, //主营业务
          storeLocation: settings.storeLocation, //店铺地址
          scrollText: settings.scrollText, //滚动字幕
          phone: settings.phone,
          //-------------------6. 运费计价规则
          deliveryRules: settings.deliveryRules || [],
        })
      })
      .catch(function (res) {
        wx.hideLoading();
      })
  },

  // ------------------------------------开门时间联动
  bindOpenTimeChange: function (e) {
    this.setData({
      openTime: e.detail.value
    })
  },
  // ------------------------------------关门时间联动
  bindCloseTimeChange: function (e) {
    this.setData({
      closeTime: e.detail.value
    })
  },
  // ------------------------------------外卖正常配送收费 时间1
  bindNormalTimeStartChange: function (e) {
    this.setData({
      normalTimeStart: e.detail.value
    })
  },
  // ------------------------------------外卖正常配送收费 时间2
  bindNormalTimeEndChange: function (e) {
    this.setData({
      normalTimeEnd: e.detail.value
    })
  },
  // ----------------------------------- 配送费计价规则设置输入框 input &  switch
  onBindDeliveryRulesInput(e) {
    let {
      idx,
      param
    } = e.currentTarget.dataset;
    let value;
    if (e.type === "change") {
      // switch 类型输入
      value = e.detail.value ? true : false;
    } else {
      // input 数字类型输入
      value = parseInt(e.detail.value);
    }
    this.setData({
      [`deliveryRules[${idx}].${param}`]: value
    })
  },
  onRangeDelete(e) {
    let {
      idx,
      param
    } = e.currentTarget.dataset;
    this.data.deliveryRules.splice(idx, 1)
    this.setData({
      deliveryRules: this.data.deliveryRules
    })
  },
  addDeliveryRange() {
    // 1. 判断计价规则是否为空
    let rules = this.data.deliveryRules;
    let lastItem;
    let item;
    lastItem = rules && rules.length > 0 ? rules[rules.length - 1] : null;

    // a. 向空规则中新增规则
    if (!lastItem) {
      item = {
        "rangeLeft": 0,
        "rangeRight": this.data.sendDistance, // 默认值为最远配送距离
        "enableOrderMinCharge": true,
        "minCharge": 25,
        "baseDeliveryCost": 3, // 基础配送费用
        "enableDeliveryDiscount": false,
        "orderMoneyLimit": 0, // 运费优惠的最低金额
        "deliveryDiscount": 0 // 运费优惠金额
      }
    }else{
      // 向已有规则中继续添加规则
      item = {
        "rangeLeft": lastItem.rangeRight,
        "rangeRight": this.data.sendDistance, // 默认值为最远配送距离
        "enableOrderMinCharge": true,
        "minCharge": 25,
        "baseDeliveryCost": 3, // 基础配送费用
        "enableDeliveryDiscount": false,
        "orderMoneyLimit": 0, // 运费优惠的最低金额
        "deliveryDiscount": 0 // 运费优惠金额
      }
    }
    this.data.deliveryRules.push(item);
    this.setData({
      deliveryRules: this.data.deliveryRules
    })
  },
  // ------------------------------------保存设置
  formSubmit: function (e) {
    wx.showLoading({
      title: '正在保存'
    })
    console.log(e.detail.value)
    let settings = e.detail.value;
    settings.deliveryRules = this.data.deliveryRules;
    wx.cloud.callFunction({
      name: 'updateSettings',
      data: {
        settings: settings
      }
    }).then(res => {
      wx.hideLoading() //关闭加载
      if (res.result.result == 'success') {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
        })
      } else {
        wx.showModal({
          title: '友情提示',
          content: '保存失败，请稍后再试',
          showCancel: false
        })
      }
    }).catch(res => {
      console.log(res.result)
      wx.showModal({
        title: '友情提示',
        content: '保存失败，请稍后再试',
        showCancel: false
      })
    })
  }
})